package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class OperationLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Around("@annotation(com.itheima.aop.LogOperation)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //开始时间
        long  start=System.currentTimeMillis();
        log.info("操作日志记录开始...");
        //创建操作日志对象
        OperateLog operateLog = new OperateLog();
        //给log实体类赋值, 操作时间为当前系统时间
        operateLog.setOperateTime(LocalDateTime.now());
        //获取类名
        String clsName = joinPoint.getTarget().getClass().getName();
        operateLog.setClassName(clsName);
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        operateLog.setMethodName(methodName);
        //获取参数
        Object[] args = joinPoint.getArgs();
        operateLog.setMethodParams(Arrays.toString( args));
        //ThreadLocal,TokenFilter校验时，解析得到登录用户id，存入ThreadLocal中
        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());

        Object result = null;
        try {
            //调用目标方法
            result = joinPoint.proceed();
            //记录方法执行的返回值
            operateLog.setReturnValue(result==null?"":result.toString());
        } finally {
            // 记录方法执行耗时
            operateLog.setCostTime(System.currentTimeMillis() - start);
            // 保存到数据库表中
            operateLogMapper.insert(operateLog);
        }
        log.info("操作日志记录结束...");
        return result;
    }
}
